// ==UserScript==
// @name           VisualizationScript
// @namespace      http://picasaweb.google.com/
// @description    A simple visualization for metadata in comments of images.
// @include        http://picasaweb.google.com/*
// ==/UserScript==


writeout();
fixButtons();
var baseUrl = "http://chart.apis.google.com/chart?";
resizeBoxes();

//function for adding output

function writeout(){
	

	var sibNode = document.getElementById("lhid_main");
	if (!sibNode.childNodes[4].firstChild)
	{

		setTimeout(writeout, 1000);
		return;
	}



	clearImages();

	var mainBox = document.getElementById("lhid_main");
	
	var comments = mainBox.childNodes[3].firstChild.firstChild.firstChild.childNodes;
	
	for (var i = 0; i < comments.length; i++)
	{
		if (comments[i].className == "lhcl_ownercomment")
	      		continue;

	    
		var imageUrl = cleanLabel(comments[i].textContent);
		insertImage(baseUrl + imageUrl);
	  }

}

function cleanLabel(commentString)
{
  var itemUrl = commentString.split(": ")[1];
  return itemUrl;

}

// Builds the img object and inserts it into the document
function insertImage(imageUrl)
{
	// Now we can insert the chart

	var image = document.createElement("img");
	image.src = imageUrl;
	image.setAttribute("class", "lhcl_tools");

	var insertion = document.getElementById("chartDiv");

	if (!insertion)
	{
		var chartDiv = document.createElement("div");
		chartDiv.id = "chartDiv";
		chartDiv.clear = "top";
		chartDiv.style.backgroundColor = "#FFFFFF";
		chartDiv.style.border = "1px solid #CCCCCC";
		chartDiv.style.margin = "0pt 7px 7px 0pt";
		chartDiv.style.width = "350px";

		// chartDiv.setAttribute("class", "lhcl_prettybox lhcl_sidebox lhcl_recordbox");
		var insertionPoint = document.getElementById("lhid_rightbox").childNodes[1];
		insertionPoint.insertBefore(chartDiv, insertionPoint.childNodes[0]);
		document.getElementById("chartDiv").appendChild(image);
	}
	else
	{
		document.getElementById("chartDiv").appendChild(image);
	}
	
}

// Clears the chart image
function clearImages()
{
	var insertion = document.getElementById("chartDiv");
	
	if (!insertion)
	{
		return;
	}
	
	var children = insertion.childNodes;

	var max = children.length

	for (var i = 0; i < max ;i++)
	{
		child = children[0];
		document.getElementById("chartDiv").removeChild(child);
	}
	    

}

// Sets next and previous buttons to generate a new chart
function fixButtons() {
	var checkReady = document.getElementById("nextbox");
	if (!checkReady)
	{
		setTimeout(fixButtons, 1000);
		return;
	}
	
	var nextNode = document.getElementById("nextbox");
	nextNode.setAttribute("onclick", "setTimeout(writeout, 1000); return false;", 0);
	
	var prevNode = document.getElementById("prevbox");
	prevNode.setAttribute("onclick", "setTimeout(writeout, 1000); return false;", 0);




}


function resizeBoxes()
{
  var mainBox = document.getElementById("lhid_main");
  mainBox.style.width = "80%";
  

}

